<template>
  <div>
    <BasicTable
      @register="registerTable"
      title="仓库出入库信息管理"
      :pagination="false"
      :scroll="{ x: false, y: 'calc(100vh - 300px)' }"
    >
      <template #deptid="{ column, record }">
        {{
          treeToArray(deptData).filter((item) => item.key == record.deptid).length > 0
            ? treeToArray(deptData).filter((item) => item.key == record.deptid)[0].title
            : record.deptid
        }}
      </template>

      <template #action="{ column, record }">
        <TableAction
          :actions="[
            {
              icon: 'ant-design:file-search-outlined',
              label: '出入库记录',
              onClick: onViewWareHouseInventoryRecordButtonClick.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <ViewWareHouseInventoryRecord
      @register="registerViewWareHouseInventoryRecordDrawer"
      :orgcode="orgcode"
      @success="afterSuccess"
      :mode="mode"
    />
  </div>
</template>

<script lang="ts">
  import { defineComponent, onMounted, ref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { useGlobSetting } from '/@/hooks/setting';
  import { Tag } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { queryUserValidWareHouse } from '/@/api/ehs/warehouse';
  import { warehouseIventoryTableColumns } from './warehouseInventory.data';
  import { getUserOrganization, getOrgDeptTree } from '/@/api/ehs/organization';
  import ViewWareHouseInventoryRecord from './ViewWareHouseInventoryRecord.vue';
  import { useDrawer } from '/@/components/Drawer';
  export default defineComponent({
    name: 'warehouseIventoryIndex',
    components: { BasicTable, TableAction, Tag, ViewWareHouseInventoryRecord },
    props: ['mode'],
    setup(props, { emit }) {
      const orgcode = ref('');
      const deptData = ref([]);
      const { globalProjectCode } = useGlobSetting();
      const projectCode = ref<String>(globalProjectCode);
      const [
        registerViewWareHouseInventoryRecordDrawer,
        { openDrawer: openViewWareHouseInventoryRecordDrawer },
      ] = useDrawer();
      const [registerTable, { reload }] = useTable({
        api: queryUserValidWareHouse,
        columns: warehouseIventoryTableColumns,
        canResize: true,
        striped: true,
        showTableSetting: true,
        showIndexColumn: true,
        isTreeTable: false,
        bordered: true,
        immediate: false,
        ellipsis: true,
        useSearchForm: false,
        indexColumnProps: {
          width: 50,
        },
        beforeFetch: (params) => {
          params = orgcode.value;
          return params;
        },
        actionColumn: {
          width: 150,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });
      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        reload();
      }

      function onViewWareHouseInventoryRecordButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '仓库出入库管理',
          operateType: OperationTypeEnum.VIEW,
          orgcode: orgcode.value,
          dataId: record.id,
        };
        openViewWareHouseInventoryRecordDrawer(true, propsData);
      }

      // tree结构扁平化
      function treeToArray(treeNodes) {
        let result = [];

        //递归函数 traverse，用于处理单个节点
        function traverse(node, fatherId) {
          const newNode = { ...node };
          if (fatherId) {
            newNode.fatherId = fatherId;
          }
          delete newNode.children;
          // 将没有子节点的新节点添加到结果数组中
          result.push(newNode);

          // 如果当前节点包含 children 属性（即有子节点）
          if (node.children) {
            node.children.forEach((item) => {
              traverse(item, newNode.code);
            });
          }
        }

        treeNodes.forEach(traverse);

        return result;
      }

      onMounted(() => {
        getUserOrganization(globalProjectCode).then((res) => {
          orgcode.value = res.orgcode;
          getOrgDeptTree(res.orgcode)
            .then((res) => {
              if (res) {
                deptData.value = res;
              }
            })
            .catch((e) => {});
          reload();
        });
      });
      return {
        orgcode,
        deptData,
        treeToArray,
        registerTable,
        afterSuccess,
        onViewWareHouseInventoryRecordButtonClick,
        registerViewWareHouseInventoryRecordDrawer,
      };
    },
  });
</script>

<style scoped></style>
